package com.polaris.live.popup.party

import android.content.Context
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.StringUtils
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BottomPopupView
import com.polaris.live.R
import com.polaris.live.adapter.party.RoomInfoMemberNowAdapter
import com.polaris.live.common.network.request
import com.polaris.live.common.network.requestLoading
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.databinding.PopupMembershipFeeBinding
import com.polaris.live.net.liveService
import com.polaris.live.resp.go_resp.UpdateMemberRequest
import com.polaris.live.translation.R.string
import com.polaris.live.viewmodel.party.PartyAnchorFragmentModel
import com.polaris.live.widget.refresh.EmptyView

/**
 * 成员费
 *
 * @author Created by 天晴 on 2024/10/15 19:18
 * @since 1.0.0
 **/
class MembershipFeePopup(
    context: Context,
    val mViewModel: PartyAnchorFragmentModel,
    val roomId: String,
    val onClick: ((userId: Long) -> Unit)? = null,
) : BottomPopupView(context) {

    private lateinit var mBinding: PopupMembershipFeeBinding
    override fun getImplLayoutId(): Int {
        return R.layout.popup_membership_fee
    }

    private val mAdapter: RoomInfoMemberNowAdapter by lazy {
        RoomInfoMemberNowAdapter()
    }
    private val emptyView by lazy {
        EmptyView(context).apply {
            setEmptyTip(
                R.drawable.salalogo,
                StringUtils.getString(string.no_members_joined)
            )
        }
    }

    private var remaining: Long? = null //剩余次数
    override fun onCreate() {
        super.onCreate()
        mBinding = PopupMembershipFeeBinding.bind(popupImplView)

        getMembersPrice()
        membersRecently()

        updateRemaining()

        mBinding.recycler.apply {
            layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
            itemAnimator = null
            adapter = mAdapter
        }
        mAdapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.av_fv -> {
                    onClick?.let { click ->
                        mAdapter.getItemOrNull(position)?.let {
                            dismiss()
                            click.invoke(it.user.userId)
                        }
                    }
                }
            }
        }


        mBinding.btnClose.setOnClickListener {
            dismiss()
        }
        mBinding.okBtn.setOnClickListener {
            upDateMembersPrice()
        }
        mBinding.btnTips.setOnClickListener {
            MembershipFeeExplanationPopup.show(context)
        }
        mBinding.refreshView.setOnLoadMoreListener {
            ++pageNumber
            membersRecently()
        }
        mBinding.refreshView.setOnRefreshListener {
            pageNumber = 0
            membersRecently()
        }
    }

    /**
     * 获取当前价格
     */
    private fun getMembersPrice() {
        mViewModel.request({
            liveService.membersPrice()
        }, {
            if (it.price > 0) {
                mBinding.edit.setText("${it.price}")
            }
            remaining = it.remaining
            updateRemaining()
        })
    }

    private fun updateRemaining() {
        if (remaining == null) {
            mBinding.tvModificationsToday.visibility = View.GONE
        } else {
            mBinding.tvModificationsToday.visibility = View.VISIBLE
            mBinding.tvModificationsToday.text =
                StringUtils.getString(string.remaining_modifications_today, remaining)
        }

    }

    /**
     * 更新房间成员价格
     */
    private fun upDateMembersPrice() {
        val priceText = mBinding.edit.text?.toString()
        if (priceText.isNullOrEmpty()) {
            ToastGravity.showGravity(string.please_membership_fee)
            return
        }
        val price = priceText.toLongOrNull() ?: 0L
        val isMultipleOfTen = (price % 10 == 0L)
        if (!isMultipleOfTen) {
            ToastGravity.showGravity(string.the_membership_10)
            return
        }
        if (price > 10000) {
            ToastGravity.showGravity(string.the_membership_10000)
            return
        }
        mViewModel.requestLoading({
            liveService.upDateMembersPrice(UpdateMemberRequest(price))
        }, {
            remaining = it.remaining

            updateRemaining()
            ToastGravity.showGravity(string.modified_successfully)
            dismiss()
        }, {
            ToastGravity.showGravity(it.errorMsg)
        })
    }

    var pageNumber: Long = 0
    val pageSize: Long = 20

    /**
     * 获取最近成为的成员
     */
    private fun membersRecently() {
        mViewModel.request({
            liveService.membersRecently(roomId, pageNumber, pageSize)
        }, {
            mBinding.widgetLoading.visibility = View.GONE
            if (pageNumber == 0L) {
                mAdapter.data.clear()
                mAdapter.setList(it.list)
            } else {
                mAdapter.addData(it.list)
            }
            if (pageNumber == 0L) {
                mBinding.refreshView.finishRefresh()
            } else {
                mBinding.refreshView.finishLoadMore(0)
            }
            if (it.hasMore) {
                mBinding.refreshView.setEnableLoadMore(true)
            } else {
                mBinding.refreshView.setEnableLoadMore(false)
            }

        }, {
            mBinding.widgetLoading.visibility = View.GONE
            if (pageNumber == 0L) {
                mBinding.refreshView.finishRefresh(false)
                mBinding.refreshView.setEnableLoadMore(false)
                mAdapter.setEmptyView(emptyView)
            } else {
                mBinding.refreshView.finishLoadMore(0, false, false)
            }
            if (mAdapter.data.isNotEmpty()) {
                ToastGravity.showGravity(it.errorMsg)
            }
        })
    }

    companion object {

        fun show(
            context: Context,
            mViewModel: PartyAnchorFragmentModel,
            roomId: String,
            onClick: ((userId: Long) -> Unit)? = null,
        ) {
            XPopup.Builder(context)
                .isViewMode(false)
                .hasNavigationBar(false)
                .hasShadowBg(true)
                .enableDrag(false)
                .moveUpToKeyboard(false)
                .autoFocusEditText(false)
                .isDestroyOnDismiss(true)
                .asCustom(MembershipFeePopup(context, mViewModel, roomId, onClick))
                .show()
        }
    }
}